package com.wolf.client;

import com.wolf.core.Protocol;
import com.wolf.core.RequestEntity;
import com.wolf.core.ResponseEntity;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.DefaultEventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.DefaultPromise;

import java.util.concurrent.ExecutionException;

/**
 * @auth: dylan
 * @Desc:
 * @Time: 2024/5/1
 */
public class WolfNettyClient {

    private String host;
    private int port;
    private Bootstrap bootstrap;
    private EventLoopGroup workGroup;

    public WolfNettyClient(String host,int port) {
        this.port = port;
        this.host=host;
        init();
    }

    private void init() {
            bootstrap = new Bootstrap();
            workGroup = new NioEventLoopGroup(5);
            bootstrap.group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new WolfClientInitialHandler());
    }

    public Object sendRequest(Protocol<RequestEntity> protocol) throws ExecutionException, InterruptedException {
        ChannelFuture future = bootstrap.connect(this.host, this.port).sync();
        System.out.println("connect success!");
        DefaultPromise<Protocol<ResponseEntity>> promise = new DefaultPromise<>(new DefaultEventLoop());
        Holder.REQ_RESULT_MAP.put(protocol.getHeader().getSerialId(), promise);
        future.channel().writeAndFlush(protocol);
        String result = String.valueOf(promise.get());
        System.out.println("get Result from rpc");
        future.channel().close();
        workGroup.shutdownGracefully();
        return result;
    }
}
